package com.example.api.Service;

import com.example.api.Entity.Student;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StudentService {
    private List<Student> students = new ArrayList<>();

    public StudentService(){
        // 初始化一些学生数据
        students.add(new Student(1L,"zhangsan","san","zahng.san@example.com",20));
        students.add(new Student(2l,"lisi","si","li.si@example.com",21));
    }

    public List<Student> findAllStudents() {
        return students;
    }

    public Student findStudentById(Long id){
        for (Student student : students){
            if (student.getId().equals(id)){
                return student;
            }
        }
        return null;
    }

    public Student createStudent(Student student) {
        // 自动生成学生id
        Long id = students.isEmpty() ? 1L : students.get(students.size() - 1).getId() + 1;
        student.setId(id);
        students.add(student);
        return student;
    }

    public Student updateStudent(Long id, Student updatedStudent) {
        for ( int i = 0; i< students.size(); i++){
            if (students.get(i).getId().equals(id)){
                updatedStudent.setId(id);
                students.set(i,updatedStudent);
                return updatedStudent;
            }
        }
        return null;
    }

    public boolean deleteStudent(Long id){
        for (Student student : students){
            if (student.getId().equals(id)){
                students.remove(student);
                return true;
            }
        }
        return false;
    }
}
